<?php

	session_start();	

	if($_SESSION["logged"] == false)
	{
		header("Location: login.php");
		exit();
	}
	
	include("include/db.inc");
	
	if($_GET["hash"] == null)
		header("Location: index.php");		
	else if($_GET["hash"] == "")
		header("Location: index.php");
		
	$db = new db_Connection();
	$db->Connect();
	
	$infohash = $_GET["hash"];

	$sql = "SELECT * FROM Torrent WHERE INFO_HASH='$infohash'";
	$result = mysql_query($sql) or die('Query failed: ' . mysql_error());	
	if(!($line = mysql_fetch_array($result, MYSQL_ASSOC)))
	{
		if($result)
			mysql_free_result($result);
			
		echo ("Torrent does not exist!");
		exit();
	}
	
	$metainfo = $line["metainfo"];
	
	$ind = strpos($metainfo, '/announce');	
	$default_passkey = substr($metainfo, $ind - 20, 20);
	
	$passkey = $_SESSION["passkey"];	
	
	header('Content-type: application/x-bittorrent');
	header('Content-Disposition: attachment; filename="trt.torrent"');
	
	echo substr($metainfo, 0, strpos($metainfo, $default_passkey));
	echo $passkey;
	echo substr($metainfo, $ind, strlen($metainfo) - $ind);
	
	
	if($result)
		mysql_free_result($result);
?>